// app/controller/home.js
const Controller = require('../core/base_controller');

class HouseRingController extends Controller {
  async HouseRingList() {
    
    const sql = `select * from house_ring 
          left join t_broker_user on house_ring.b_id=t_broker_user.b_id
          `
    const ringList = await this.app.mysql.query(sql);
    const newRing = ringList.map(item=>{
      const {content,img_list,time,b_avatar,b_nickname,id} = item;
      return{
        content,img_list,time,b_avatar,b_nickname,id
      }
    })
    this.ctx.body = {
      meta:{
        status:200,
        msg:"获取动态成功"
      },
      data:{
        list:newRing
      }
    }
  }

  async addHouseRing(){
    const {id} = this.ctx.state.user
    const [files,fields] = await this.multiUpload();
    const {content} = fields;
    if(!files.length) return this.ctx.body = {meta: {msg: "必传项未传", status: 203,},};
    const result = await this.app.mysql.insert('house_ring', {
      img_list:files.toString(),
      time:new Date().getTime(),
      content,
      b_id:id,  
    });

    if(result.affectedRows === 1){
      this.ctx.body = {
        meta:{
          status:200,
          msg:"发布成功"
        },
      }
     } else {
      this.ctx.body = {
        meta:{
          status:203,
          msg:"发布失败"
        },
      }
     }
  }
  
  async delHouseRing(){
    const {id} = this.ctx.state.user
    const {id:ring_id} = this.ctx.request.body;
    const flag = await this.app.mysql.get('house_ring', { id: ring_id });
    if(flag.b_id!==id) return this.ctx.body = {meta: {msg: "无权删除他人动态", status: 203,},};
    const result = await this.app.mysql.delete('house_ring', {
     id:ring_id
    });
    if(result.affectedRows !==1) return this.ctx.body = {meta: {msg: "删除失败", status: 203,},};
    this.ctx.body = {meta: {msg: "删除成功", status: 200,},};
  }
}

module.exports = HouseRingController;